class Slideshow < ActiveRecord::Base
  
  has_many :slideshow_images, :order => "position ASC", :dependent => :destroy
  file_column :sound_url 
  validates_format_of :sound_url, 
    :if => Proc.new{|s| s.sound_url},
    :with    => %r{\.(mp3)$}i,
    :message => "must be a URL for a MP3 file"
  
  #Returns the duration of the slideshow in seconds.
  def duration
    SlideshowImage.sum(:duration, :conditions => ['slideshow_id=?', id])
  end
  
  #Returns duration of the sound file in seconds or nil if none found.
  def mp3_duration
    path = sound_abs_path
    if path
      Mp3Info.open(path) do |mp3info|
        mp3info.length 
      end
    else
      nil
    end
  end
  
  #Returns absolute path to the sound file or nil if none found.
  def sound_abs_path
    if sound_url
    "#{RAILS_ROOT}/public/slideshow/sound_url/" + id.to_s + "/" + read_attribute(:sound_url)
    else
      nil
    end
  end
  
  #Returns position of current last slide.
  def current_position
    current = SlideshowImage.maximum(:position, :conditions => ['slideshow_id=?',id])
    current = -1 if current.nil?
    current
  end
  
  #Returns position of slide to be added.
  def next_position
    current_position + 1
  end
      
  def ecase
    ref = reference
    ref && ((ref.class == Ecase) ? ref : ref.ecase)  
  end

  def reference
    ref = Ecase.find_by_slideshow_id(id)

    if ref.nil?
      ref = Event.find_by_slideshow_id(id)
    end

    ref
  end
  
  #Returns relative path to xml for this slideshow
  def xml_path
    "slideshows/generate_xml/" + id.to_s
  end
end